<?php
include_once "dao/UserAccountDAO.php";

$func = $_POST['func'];

if($func==("checkEmail")) {
	checkEmailExists($_POST['emailAddress']);
	
}
else if ($func==("registerUser")){
	registerUser();
}

	
	
	
function checkEmailExists($emailAddress) {
	
	$userAccountDAO = new UserAccountDAO();
	
	
	header('Content-type: application/json');
    echo json_encode($userAccountDAO->checkEmailExists($emailAddress));
    $userAccountDAO->close();
    
}

function registerUser() {
	$name = $_POST['name'];
	$surname = $_POST['surname'];
	$emailAddress = $_POST['emailAddress'];
	$password = $_POST['password1'];
	$activationKey = mt_rand(). mt_rand(). mt_rand(). mt_rand() . time();
	
	
	$userAccountDAO = new UserAccountDAO();
	
	$userAccountDAO->createAccount($name, $surname, $emailAddress, $password, $activationKey);
	
	sendActivationMail($emailAddress, $activationKey);
	
	echo "An email has been sent to $emailAddress with an activation key. Please check your mail to complete registration.";
	
	/*
	header( 'Location: http://localhost/FYP/index.php');
 	exit();
 	*/
 	
}
//send the activation mail to user
function sendActivationMail($emailAddress, $activationKey) {
	
	$host = "ssl://smtp.gmail.com";
	$port = "465";
	$username = "frosty1986@gmail.com";
	$password = "dtaewidq1";
	
	$subject = "Fam Tree.com Registration";
	$message = "Welcome to our website!\r\rYou, or someone using your email address, has completed registration at famtree.com. You can complete registration by clicking the following link:\rhttp://localhost/UserAccount.php?func=verify&activationKey=$activationKey\r\rIf this is an error, ignore this email and you will be removed from our mailing list.\r\rRegards,\ FamTree.com Team";
	
	$headers = 'From: noreply@ famtree.com' . "\r\n" .

    'Reply-To: noreply@ famtree.com' . "\r\n" .

    'X-Mailer: PHP/' . phpversion();
	
	
	$smtp->send($emailAddress, $subject, $message, $headers);
	
}


?>